<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2022/12/5
 * Time: 17:15
 */

namespace app\model\app;


use think\Model;

class AppPay extends Model
{
    public static function http_post($url, $data)
    {
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'application/json',
                'content' => $data,
                'timeout' => 15 * 60
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    public static function http_post_res($postdata,$url = "https://payment.qeapay.com/pay/web",$is_head = false,$is_post = 1,$token = false)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url); //支付请求地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if ($is_post == 1)
            curl_setopt($ch, CURLOPT_POST, true);
        else
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        if ($is_head == true) {
            $data_string = json_encode($postdata);
            $header = [
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string)
            ];
            if ($token == true){
                $header[] = 'authorization:Bearer '.cache('pay2');
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        }else {
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata));
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response=curl_exec($ch);

        //$res=simplexml_load_string($response);

        curl_close($ch);

        return  $response;
    }


    public static function convToGBK($str) {
        if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" ) {
            return  iconv("utf-8","gbk",$str);
        } else {
            return $str;
        }
    }


    public static function sign($signSource,$key) {
        if (!empty($key)) {
            $signSource = $signSource."&key=".$key;
        }
        return     md5($signSource);
    }



    public static function validateSignByKey($signSource, $key, $retsign) {
        if (!empty($key)) {
            $signSource = $signSource."&key=".$key;
        }
        $signkey = md5($signSource);
        if($signkey == $retsign){
            return true;
        }
        return false;
    }
}